<!--
 * @Author: early-autumn
 * @Date: 2020-05-27 09:48:11
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 16:01:15
-->
<template>
  <el-dialog
    title="发送短信"
    width="640px"
    :visible="value"
    @close="handleClose"
  >
    <el-tabs>
      <el-tab-pane label="短信">
        <el-form>
          <el-form-item label="短信模板">
            <el-cascader
              v-if="value"
              :options="options"
              @change="handleSmstemplate"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="短信内容">
            <div class="content">
              <template v-for="text in content">
                <el-input
                  v-if="inputs[text]"
                  :key="text"
                  v-model="form[text]"
                  class="content__input"
                  :placeholder="inputs[text]"
                ></el-input>
                <span v-else :key="text">{{ text }}</span>
              </template>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-tabs>
      <el-tab-pane label="接收人">
        <el-popover v-for="item in data" :key="item.id" trigger="click">
          <table-phone
            style="width: 150px"
            :phones="item.selectPhoneNumber"
            @click="(e) => handlePhone(e, item)"
          ></table-phone>
          <el-button slot="reference" style="margin: 0 10px 10px 0">
            {{ item.customerName }} {{ item.phoneNumber }}
          </el-button>
        </el-popover>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import TablePhone from '@/components/yiya/TablePhone'
import smstemplates from '@/utils/smstemplates'
import { sendTextMessage } from '@/api/services/common'

const replaceValues = {
  '${customerName}': '__customerName__',
  '${doctor}': '__doctor__',
  '${time}': '__time__',
  '${phone}': '__phone__',
  '${outpatientName}': '__outpatientName__',
  '${address}': '__address__',
  '${transportation}': '__transportation__',
}

export default {
  name: 'SendMessage',
  components: {
    TablePhone,
  },
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    type: {
      type: [Number, String],
      default: 1,
    },
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loading: false,
      templateCode: undefined,
      content: [],
      inputs: {
        customerName: '请输入客户姓名',
        doctor: '请输入医生姓名',
        time: '请输入时间',
        phone: '请输入门诊电话',
        outpatientName: '请输入门诊名称',
        address: '请输入门诊地址',
        transportation: '请输入到达方式',
      },
      form: {},
    }
  },
  computed: {
    ...mapState({
      department: (state) => state.clinic.department,
    }),
    // 单发
    singleShot() {
      return this.data.length === 1
    },
    options() {
      return smstemplates.map(({ title, smslist }) => ({
        label: title,
        value: title,
        children: smslist
          .filter(({ content }) =>
            this.singleShot ? content.indexOf('${customerName}') === -1 : true
          )
          .map(({ title, content, code }) => ({
            label: title,
            value: {
              content,
              code,
            },
          })),
      }))
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
      }
    },
  },
  methods: {
    init() {
      this.templateCode = undefined
      this.content = []
    },
    handleSmstemplate([, smstemplate]) {
      const { deptName, phone, address, transportation } = this.department
      const [customer] = this.data
      const clinic = {
        outpatientName: deptName,
        address,
        phone,
        transportation,
      }
      const form = {}
      this.templateCode = smstemplate.code
      this.content = Object.entries(replaceValues)
        .reduce((content, [key, value]) => {
          const dot = value.split('__').join('')
          if (content.indexOf(dot) !== -1) {
            if (customer[dot]) {
              form[dot] = customer[dot]
            } else if (clinic[dot]) {
              form[dot] = clinic[dot]
            } else {
              form[dot] = ''
            }
          }
          return content.replace(key, value)
        }, smstemplate.content)
        .split('__')
      this.form = form
    },
    handlePhone(e, p) {
      p.phoneNumber = e.phoneNumber
    },
    async handleSubmit() {
      if (this.templateCode === undefined) {
        this.$message.error('请选择短信模板')
        return
      }
      if (Object.values(this.form).some((value) => !value)) {
        this.$message.error('请输入完整信息')
        return
      }
      try {
        this.loading = true
        await sendTextMessage({
          type: this.type,
          ids: this.data.map((item) => item.id).join(','),
          shopName: this.department.deptName,
          templateCode: this.templateCode,
          templateParam: JSON.stringify(this.form),
        })
        this.handleClose()
        this.$emit('ok')
      } finally {
        this.loading = false
      }
    },
    handleClose() {
      this.$emit('close', false)
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  width: 600px;
  padding: 15px;
  display: inline-block;
  background-color: #f6f6f6;

  .content__input {
    width: 150px;
    // flex-shrink: 0;
    // display: inline-block;
  }
}
</style>
